package com.ruoyi.iot.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.backendEnum.SensorException;
import com.ruoyi.iot.dto.Sensor;
import com.ruoyi.iot.mapper.SensorMapper;
import com.ruoyi.iot.service.SensorService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class SensorServiceImpl implements SensorService {

    private  final SensorMapper sensorMapper;

    @Override
    public void upload(Sensor sensor) {
        String sensorId = getSensorId(sensor);
        sensor.setSensorId(sensorId);
        sensorMapper.upload(sensor);
    }

    @Override
    public void delete(String id) {
        if (sensorMapper.getCountSensorId(id) == 0){
            throw new ServiceException(SensorException.SENSOR_DATA_NOT_EXIST);
        }
        sensorMapper.delete(id);
    }

    @Override
    public List<Sensor> search(String mineId, String sensorType, Integer runningState) {
        List<Sensor> sensorList = sensorMapper.search(mineId, sensorType, runningState);
//        if (sensorList.isEmpty()){
//            throw new ServiceException(SensorException.SENSOR_DATA_NOT_FOUND);
//        }
        return sensorMapper.search(mineId,sensorType,runningState);
    }

    @Override
    public void update(Sensor sensor) {
        if (sensorMapper.getCountSensorId(sensor.getSensorId()) == 0){
            throw new ServiceException(SensorException.SENSOR_DATA_NOT_EXIST);
        }
        sensorMapper.update(sensor);
    }

    @Override
    public List<Sensor> searchAll() {
        return sensorMapper.searchAll();
    }

    @Override
    public String getNewSensorId() {
        return sensorMapper.getNewSensorId();
    }

    private String getSensorId(Sensor sensor) {
        // FF为传感器类型，确保两位
        String sensorTypeCode = String.format("%02d", Integer.parseInt(sensor.getSensorType()));

        // 查找最后一个传感器
        String lastSensorId = sensorMapper.getNewSensorId();

        String sensorDataNumber = "00001"; // 默认传感器数据编号
        if (lastSensorId != null) {
            int lastNumber = Integer.parseInt(lastSensorId.substring(lastSensorId.length() - 5));
            // 自增并确保五位
            sensorDataNumber = String.format("%05d", lastNumber + 1);
        }

        return sensor.getMineId() +sensorTypeCode + sensorDataNumber;
    }
}
